/*jslint sloppy: true */
/*global require */
require('./runner.html');
var probe = require('../global');
var angular = require('angular');

probe.controller('LCRunner', function ($location, $scope, Task, $q,
										Result, $window, LC, $element, simulight) {
	var task, caseIndex = 0,
		uploadResult = $q.defer(),
		rA = [],
		ciList = [],
		bootArgs = $location.search(),
		auth = { probe: bootArgs.probe, token: bootArgs.token };

	LC.init($element[0], function () {
		$element.css({ position: 'fixed', width: '100%', height: '100%',
			top: 0, left: 0, margin: 0 });
		$scope.lemoncaseFrame = angular.element(this).css({ 'border': 'none' });
	});

	if (!bootArgs.id) {
		$window.alert('没有指定要执行的内容');
		throw new Error('No case or task was be selected for running.');
	}

	$scope.task = task = Task.get(angular.extend({ taskId: bootArgs.id }, auth), function () {
		var cOL = $scope.caseList = angular.fromJson(task.schemas).caseList;
		angular.forEach(cOL, function (cO) {
			ciList.push({
				name: cO.name,
				ci: new LC.Case(LC.parse(cO.code), {})
			});
		});

		$scope.ciHEAD = ciList[0];
		$scope.ciHEAD.ci.start();
		$scope.index = 0;
	});

	LC.setup({
		successCallback: function () {
			rA.push({
				log: $scope.ciHEAD.ci.getLog().export2json()
			});

			$scope.ciHEAD = ciList[caseIndex += 1];
			$scope.index = caseIndex;

			if ($scope.ciHEAD) {
				$scope.ciHEAD.ci.start();
			} else {
				$window.alert('执行完毕，点击确定上传测试日志');
				uploadResult.resolve(rA);
			}

			$scope.$apply();
		},
		triggerCallback: function triggerCallback(objectDOM) {
			simulight(objectDOM, $scope.lemoncaseFrame[0]);
		}
	});

	uploadResult.promise.then(function (rA) {
		new Result({
			name: task.name + '_' + task.version +
				'_' + $scope.project.version + '_' + Date.now(),
			taskId: task.taskId,
			version: $scope.project.version,
			data: angular.toJson({
				ua: navigator.userAgent,
				platform: navigator.platform,
				taskResult: rA
			})
		}).$upload(auth, function () {
			$window.alert('上传成功，关闭页面结束本次测试');
		});
	});
});
